<template>
    <div class="content">
        <div class="zw-form-layout">
            <el-form ref="formRef" :model="form" label-width="auto">
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="角色名称" prop="roleName">
                            <el-input v-model="form.roleName" placeholder="请输入角色名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="状态" prop="isEnable">
                            <el-select v-model="form.isEnable" clearable placeholder="请选择状态">
                                <el-option
                                    v-for="item in isEnable"
                                    :key="item.value"
                                    :label="`已${item.label}`"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" class="zw-form-btns">
                        <el-button type="primary" @click="searchHandler">查询</el-button>
                        <el-button plain @click="resetHandler">清空</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <el-row>
            <el-col class="zw-table-btns">
                <el-button type="primary" @click="addHandler" v-auth="'role:add'">新建角色</el-button>
            </el-col>
        </el-row>
        <el-table :data="tableList" stripe>
            <el-table-column v-for="{ prop, ...rest } in tableColumns" :key="prop" :prop="prop" v-bind="rest">
                <template #default="{ row }">
                    <div v-if="prop === 'operations'">
                        <el-button
                            v-for="{ label, fn, ref, auth } in row.operations"
                            :key="label"
                            @click="fn(row, ref, label)"
                            :ref="el => setItemRef(el, `${ref}${row.roleId}`)"
                            size="small"
                            class="table-button"
                            v-auth="auth"
                            >{{ label }}</el-button
                        >
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination zw-pagination">
            <Pagination
                :total="totalCount"
                :page-size="form.pageSize"
                :current-page="form.pageNum"
                @sizeChange="changeSizeHandler"
                @pageChange="changePageHandler" />
        </div>
        <!-- popover弹窗 -->
        <el-popover
            popper-class="custom-role-popover-class not-close"
            ref="popoverRef"
            :virtual-ref="buttonRef"
            placement="top"
            trigger="click"
            virtual-triggering
            :width="240"
            :visible="popoverVisible">
            <div class="custom-role-popover-class-main" v-click-outside="onClickOutside">
                <!-- 删除 -->
                <h3 style="margin-bottom: 16px">
                    <el-icon class="custom-icon"><WarningFilled /></el-icon>确定要{{ currentRow.label }}该账号吗？
                </h3>
                <div style="text-align: right">
                    <el-button size="small" @click="popoverVisibleHandler()">取消</el-button>
                    <el-button size="small" type="primary" @click="popoverConfirmHandler()">确定</el-button>
                </div>
            </div>
        </el-popover>
    </div>
</template>

<script setup name="roleList">
import { ref, reactive, nextTick, onMounted, inject, onActivated, getCurrentInstance, computed } from 'vue';
import { useRouter } from 'vue-router';
import constants from '@/commons/constants';
import { packSelectObjUtil } from '@/commons/utils';
import Pagination from '@/components/Pagination.vue';
import request from '../../../../request/index';
import { ElMessage, ClickOutside as vClickOutside } from 'element-plus';
import { isNotEmpty } from '../../../../commons/utils';

const bus = inject('bus');
const confirm = inject('confirm');
const router = useRouter();
const { proxy } = getCurrentInstance();

// popover ref
let popoverVisible = ref(false);
const itemRefs = {};
const setItemRef = (el, key) => {
    if (el) {
        itemRefs[key] = el;
    }
};
const popoverRef = ref(null);
const buttonRef = ref(null);
let currentRow = reactive({
    roleId: null,
    status: null,
    label: null,
    ref: null
});

const totalCount = ref(0);
const formRef = ref(null);
const form = reactive({
    roleName: '',
    isEnable: '',
    pageNum: 1,
    pageSize: 10
});
let tableList = reactive([]);
const isEnable = reactive(packSelectObjUtil(constants.IS_ENABLED));
const operationsWidth = computed(() => {
    return (
        tableList.reduce((prev, cur) => {
            return prev > cur.operations.length ? prev : cur.operations.length;
        }, 0) * 70
    );
});
const tableColumns = computed(() => {
    return [
        { label: '角色ID', prop: 'roleId' },
        { label: '角色名称', prop: 'roleName' },
        { label: '角色说明', prop: 'remark' },
        { label: '状态', prop: 'statusText', width: '90' },
        { label: '更新时间', prop: 'updatedAt', width: '180' },
        { label: '操作', prop: 'operations', width: operationsWidth.value, fixed: 'right' }
    ];
});

/**
 * 分页查询
 */
const quertRoleListHandler = async () => {
    const res = await request('quertRoleListServ', form);
    tableList.length = 0;
    const btns = [
        { label: '编辑', fn: addHandler, ref: 'editButtonRef', auth: 'role:edit' },
        { label: '启用', fn: popoverHandler, ref: 'openButtonRef', auth: 'role:lock' },
        { label: '停用', fn: popoverHandler, ref: 'closeButtonRef', auth: 'role:lock' },
        { label: '删除', fn: popoverHandler, ref: 'removeButtonRef', auth: 'role:delete' },
        { label: '详情', fn: addHandler, ref: 'infoButtonRef', auth: 'role:info' }
    ];
    tableList.push(
        ...(res?.data?.list || []).map(item => {
            item.statusText = `已${proxy.transformStream(item.status, 'IS_ENABLED')}`;
            if (item.isDefault == 1) {
                item.operations = [btns[4]];
            } else {
                if (item.status == 1) {
                    item.operations = [btns[0], btns[2]];
                } else {
                    item.operations = [btns[0], btns[1], btns[3]];
                }
            }
            return item;
        })
    );
    totalCount.value = res.data.totalCount;
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.pageNum = 1;
    quertRoleListHandler();
};

/**
 * 重置
 */
const resetHandler = () => {
    formRef.value.resetFields();
    searchHandler();
};

/**
 * 新增/编辑
 * @param {*} row
 */
const addHandler = row => {
    if (isNotEmpty(row.roleId)) {
        router.push({
            path: '/account/roles/add',
            query: { id: row.roleId, __title__: 'editTitle' }
        });
    } else {
        router.push('/account/roles/add');
    }
};

/**
 * 修改状态
 */
const changeStatusHandler = async row => {
    const { roleId, status } = row;
    const params = {
        roleId,
        isEnable: status === 1 ? 2 : 1
    };
    const text = constants['IS_ENABLED'][params.isEnable];
    if (await confirm(`确定要${text}该角色吗？`)) {
        await request('updateRoleStatusServ', params);
        ElMessage.success('操作成功！');
        row.status = params.isEnable;
    }
};

/** 按钮组操作 */
const popoverHandler = (row, ref, label) => {
    buttonRef.value = itemRefs[`${ref}${row.roleId}`];
    Object.assign(currentRow, { ...row, ref, label });

    nextTick(() => {
        popoverVisible.value = true;
    });
};

// 点击popover外部
const onClickOutside = el => {
    popoverVisibleHandler();
};
// 控制popover展示隐藏
const popoverVisibleHandler = (visible = false) => {
    popoverVisible.value = visible;
};
// popover确定
const popoverConfirmHandler = async () => {
    const params =
        currentRow.ref === 'removeButtonRef'
            ? { id: currentRow.roleId }
            : { roleId: currentRow.roleId, isEnable: currentRow.status === 1 ? 2 : 1 };
    await request(`${currentRow.ref === 'removeButtonRef' ? 'removeRoleServ' : 'updateRoleStatusServ'}`, params);
    popoverVisibleHandler();
    searchHandler();
    ElMessage({
        type: 'success',
        message: '操作成功'
    });
};

/**
 * 分页
 * @param {*} pageNum
 */
const changePageHandler = pageNum => {
    form.pageNum = pageNum;
    quertRoleListHandler();
};

/**
 * 每页记录数修改
 * @param {*} pageSize
 */
const changeSizeHandler = pageSize => {
    form.pageNum = 1;
    form.pageSize = pageSize;
    quertRoleListHandler();
};

onMounted(() => {
    searchHandler();
});

onActivated(() => {
    quertRoleListHandler();
});
</script>
<style lang="scss">
.custom-role-popover-class {
    padding: 0px !important;
    &-main {
        padding: 16px;
    }
    h3,
    p {
        margin: 0;
    }
    h3 {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #33302d;
        display: flex;
        align-items: center;
        .custom-icon {
            width: 14px;
            height: 14px;
            margin-right: 9px;
            color: #faad14;
            margin-top: 2px;
        }
    }

    p {
        padding-left: 23px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #969696;
        line-height: 16px;
        margin: 8px 0 16px;
    }

    p + div {
        text-align: right;
    }

    .custom-preview {
        margin-top: 16px;
        display: flex;
        align-items: flex-end;
        justify-content: space-between;
    }
}
</style>
